package com.bawei.shopping2.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bawei.shopping2.R
import com.bawei.shopping2.databinding.ItemCarBinding
import com.bawei.shopping2.databinding.ItemGoodsBinding
import com.bawei.shopping2.entity.CarGoodsEntity
import com.bawei.shopping2.entity.CategoryEntity
import com.bawei.shopping2.entity.GoodsEntity

class CarGoodsAdapter(var list: MutableList<CarGoodsEntity>): RecyclerView.Adapter<CarGoodsAdapter.CarViewHolder>() {
    class CarViewHolder(var itemCarBinding: ItemCarBinding) :RecyclerView.ViewHolder(itemCarBinding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CarViewHolder {

        return CarViewHolder(ItemCarBinding.inflate(LayoutInflater.from(parent.context),parent,false))
    }
    //局部刷新
    override fun onBindViewHolder(
        holder: CarViewHolder,
        position: Int,
        payloads: MutableList<Any>
    ) {
        if (payloads.isEmpty()) {//不需要
            onBindViewHolder(holder, position);
        } else {//需要
           payloads.forEach {
               when(it){
                   "carNum"->holder.itemCarBinding.tvCarNum.text = list[position].count.toString() //重新绑定数量
                   "select"->holder.itemCarBinding.cb.isChecked = list[position].select//重新绑定选中状态
               }
           }
        }
    }
    override fun onBindViewHolder(holder: CarViewHolder, position: Int) {
        holder.itemCarBinding.carGoods = list[position]
        //item的点击事件，lambda
        holder.itemView.setOnClickListener {
            onItemClick(it,position)
        }
        //子控件的点击
        holder.itemCarBinding.ivJia.setOnClickListener{
            onItemChildClick(it,position)
        }
        holder.itemCarBinding.ivJian.setOnClickListener{
            onItemChildClick(it,position)
        }
        holder.itemCarBinding.cb.setOnClickListener{
            onItemChildClick(it,position)
        }
        holder.itemCarBinding.ivDelete.setOnClickListener{
            onItemChildClick(it,position)
        }
        holder.itemCarBinding.cb.setOnClickListener{
            onItemChildClick(it,position)
        }
    }

    override fun getItemCount(): Int {
        return list.size
    }
    //lambda表达式替换java中接口回调
    lateinit var onItemClick:(v: View, pos: Int) -> Unit   //函数类型 参数是view：position 无返回值
    lateinit var onItemChildClick:(v: View, pos: Int) -> Unit   //函数类型 参数是view：position 无返回值





    //根据下标返回对应的数据
    fun getDataByPosition(position:Int):CarGoodsEntity{
        return list[position]
    }

}